package com.dora.algorithm.huawei.printABC;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 交替打印ABC-Lock实现
 *
 * @author hanchen
 * @date 2024/12/04
 */
public class PrintABCUsingLock {

    /**
     *  控制打印次数
     */
    private int times;
    /**
     *  当前状态值：保证三个线程之间交替打印
     */
    private int state;
    private Lock lock = new ReentrantLock();

    public PrintABCUsingLock(int times) {
        this.times = times;
    }

    private void printLetter(String name, int targetNum) {
        for (int i = 0; i < times; ) {
            lock.lock();
            try {
                // 检查当前线程是否符合条件
                if (state % 3 == targetNum) {
                    state++; // 更新状态
                    i++;     // 完成一次打印
                    // 打印字符
                    System.out.println(name);
                }
            } finally {
                // 确保释放锁
                lock.unlock();
            }
            // 让出 CPU，避免线程自旋占用资源
            Thread.yield();
        }
    }

    public static void main(String[] args) {

        PrintABCUsingLock loopThread = new PrintABCUsingLock(5);

        // 启动线程 B
        new Thread(() -> {
            loopThread.printLetter("B", 1);
        }, "B").start();

        // 启动线程 A
        new Thread(() -> {
            loopThread.printLetter("A", 0);
        }, "A").start();

        // 启动线程 C
        new Thread(() -> {
            loopThread.printLetter("C", 2);
        }, "C").start();
    }
}
